#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include "cgic.h"

int fd;

int filter_func(const struct dirent *entry)
{
    // 这里可以根据需求编写过滤条件
    /*if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
    {
        return 0; // 返回非零值将被视为不符合过滤条件
    }*/
    
    if(strstr(entry->d_name, ".jpg")!= NULL)
    {
        return 1;
    }
    
    if(strstr(entry->d_name, ".png")!= NULL)
    {
        return 1;
    }

    return 0; 
}

int cgiMain()
{
    struct dirent *entry;
    struct dirent **entryList;
    int size;
    char name[32] = {0};

    //size = scandir("../Image", &entryList, filter_func, alphasort);
    size = scandir("/demo/bin/boa/www/Image", &entryList, filter_func, alphasort);
    cgiHeaderContentType("text/html");
    fprintf(cgiOut, "<HTML>\n");
    fprintf(cgiOut, "<TITLE>Picture Manage</TITLE>\n");
    fprintf(cgiOut, "<HEAD>\n");
    fprintf(cgiOut, "<link rel='stylesheet' href='../common.css'>\n");
    fprintf(cgiOut, "<script type='text/javascript' src='../image.js'></script>\n");
    fprintf(cgiOut, "</HEAD>\n");
    fprintf(cgiOut, "<BODY>\n");
    fprintf(cgiOut, "<ul class='menu'>\n");
    fprintf(cgiOut, "<li><a href='/cgi-bin/scan_dir_cgi.cgi'>Photo_Manage</a></li>\n");
    fprintf(cgiOut, "<li><a href='../ffmpeg_config.html'>Edit_URL</a></li>\n");
    fprintf(cgiOut, "<li><a href='/cgi-bin/scan_dir_cgi.cgi'>URL_Manage</a></li>\n");
    fprintf(cgiOut, "<li><a href='/cgi-bin/scan_dir_cgi.cgi'>EDIT_MP4</a></li>\n");
    fprintf(cgiOut, "<li><a href='../decode_video.html'>Remote_Moniting</a></li>\n");
    fprintf(cgiOut, "<li><a href='/cgi-bin/scan_video_cgi.cgi'>Video_Manage</a></li>\n");
    fprintf(cgiOut, "</ul>\n");

#if 0
    for (int i = 0; i < size; i++)
    {
        entry = entryList[i];
        memset(name, 0, sizeof(name));
        strcpy(name, entry->d_name);
        fprintf(cgiOut, "<br>");
        fprintf(cgiOut, "<img src=../Image/%s width=100 height=50>\n", name);
        fprintf(cgiOut, "</br>");
        fprintf(cgiOut, "<br>");
        fprintf(cgiOut, "<H3>%s</H3>", name);
        fprintf(cgiOut, "</br>");
    }
#endif

    fprintf(cgiOut, "<ul class='imagecss'>\n");
    for (int i = 0; i < size; i++)
    {
        entry = entryList[i];
        memset(name, 0, sizeof(name));
        strcpy(name, entry->d_name);
        fprintf(cgiOut, "<li>\n");
        fprintf(cgiOut, "<img id='myImage' src=/Image/%s width=50 height=100>\n", name);
        fprintf(cgiOut, "<H3>%s</H3>\n", name);
        fprintf(cgiOut, "</li>\n");
    }
    fprintf(cgiOut, "</ul>\n");
    fprintf(cgiOut, "</BODY>\n");
    fprintf(cgiOut, "</HTML>\n");
    return 0;
}
